package com.example.springbootdemo.config;

import java.sql.*;
import java.util.*;

public class MySQLMonitor {

    public static void main(String[] args) throws SQLException, InterruptedException {
        // 连接到MySQL数据库
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "username", "password");

        // 查询数据库的初始状态
        Map<String, Integer> initialData = queryData(conn);

        // 不断轮询数据库以检测数据变化
        while (true) {
            // 等待5秒钟再次轮询
            Thread.sleep(5000);

            // 查询数据库的当前状态
            Map<String, Integer> currentData = queryData(conn);

            // 将当前状态与初始状态进行比较
            for (String key : currentData.keySet()) {
                int currentValue = currentData.get(key);
                int initialValue = initialData.get(key);
                if (currentValue != initialValue) {
                    System.out.println("数据变更：" + key + "，" + initialValue + " -> " + currentValue);
                }
            }

            // 更新初始状态以反映当前状态
            initialData = currentData;
        }
    }

    // 查询数据库中的数据
    private static Map<String, Integer> queryData(Connection conn) throws SQLException {
        Map<String, Integer> data = new HashMap<String, Integer>();
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM mytable");

        while (rs.next()) {
            String key = rs.getString("key");
            int value = rs.getInt("value");
            data.put(key, value);
        }

        rs.close();
        stmt.close();

        return data;
    }
}